import { defineStore } from 'pinia'
export default defineStore('todoList', {
  state () {
    return {
      action: 'all', // all  active completed
      list: JSON.parse(window.localStorage.getItem('todos')) || [
        {
          id: 1,
          name: '睡觉',
          done: true
        },
        {
          id: 2,
          name: '玩游戏',
          done: true
        },
        {
          id: 3,
          name: '学习',
          done: false
        }
      ]
    }
  },
  actions: {
    // 修改done状态
    setDone (id) {
      //   返回值=数组.find(item=>{return boolean值})
      const findItem = this.list.find(item => item.id === id)
      findItem.done = !findItem.done
    },
    // 删除
    delList (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    // 添加
    addList (obj) {
      this.list.push(obj)
    },
    // 修改action状态
    setAction (str) {
      this.action = str
    },
    // 清除完成项
    clearDone () {
      this.list = this.list.filter(item => !item.done)
    }
  },
  getters: {
    newList () {
      return this.list.filter(item => {
        if (this.action === 'all') {
          return true
        } else if (this.action === 'active') {
          return !item.done
        } else if (this.action === 'completed') {
          return item.done
        }
      })
    }
  }
})
